<?php
namespace app\common\model;

class BonusRecord extends Base
{
	static $status = [
                0 => '未发放',
                1 => '已发放',
                2 => '发放失败',
            ];
	protected $readonly = ['id'];
	protected $auto=[];
	protected $insert=['create_time'];

	protected function setCreateTimeAttr(){
		return time();
	}

	/**
     * 获取分页列表
     * @param  [type] $where    [description]
     * @param  string $queryStr [description]
     * @param  string $baseUrl  [description]
     * @return [type]           [description]
     */
    public function getPageDatas($where,$page,$perpagenum){
        
        $start = ($page-1)*$perpagenum;
        
        $whereData=[];
        if(!empty($where)){

            if(isset($where['uid'])){
                $where['effect_uid'] = $where['uid'];
                unset($where['uid']);
            }

            foreach($where as $k => $wh):
                $whereData['a.'.$k] = $wh;
            endforeach;
        }
        
        $rows = $this
                ->alias('a')
                ->join('member b','a.reason_uid=b.id','LEFT')
                ->join('member c','a.effect_uid=c.id','LEFT')
                ->where($whereData)
                ->field('a.*,b.mid reason_mid,c.mid effect_mid')
                ->limit($start,$perpagenum)
                ->order('a.id','DESC')->select();

        $count = $this->alias('a')->where($whereData)->count();
        $data = [];
        if($count){
            foreach($rows as $row):
                $row = $row->toArray();
                $data[] = $this->setField($row);
            endforeach;
        }

        $total_page = ceil($count/$perpagenum);
        return [
            'total_page' => $total_page,
            'curent_page' => $page,
            'count' => $count,
            'data' => $data
        ];
    }

    /**
     * 处理字段数据
     * @param [type] $row [description]
     */
    public function setField($row){
        if(isset($row['coin_id'])){
            $row['coin_name'] = Coin::coinData($row['coin_id'])['coin_name'];
        }
        if(isset($row['create_time'])){
            $row['create_date'] = date("Y-m-d H:i",$row['create_time']);
        }
        if(isset($row['reason_time'])){
            $row['reason_date'] = date("Y-m-d H:i",$row['reason_time']);
        }
        if(isset($row['status'])){
            $row['status_remark'] = self::$status[$row['status']];
        }
        if(isset($row['bonus_name'])){
            $row['bonus_tag'] = Bonus::bonusData($row['bonus_name'])['bonus_tag'];
        }
        return $row;
    }

    /**
     * 领取奖金
     */
    public function receiveMemberBonus($uid){
        //时间限制
        // $timeLimit = time() - 60*60*24;
        $timeLimit = time() - 0;
        $records = $this->where(['effect_uid'=>$uid,'reason_time'=>['<=',$timeLimit],'status'=>0])->select();
        if(!$records){
            $this->error = '没有可领取的奖金';
            return false;
        }else{
            foreach($records as $record):
            	$record = $record->toArray();
                // 状态改变
                $this->where(['id'=>$record['id']])->update(['status'=>2]);
                $result = $this->receiveOneBonus($record);
                if(true===$result){
                    $this->where(['id'=>$record['id']])->update(['status'=>1,'log'=>'领取成功']);
                }else{
                    $this->where(['id'=>$record['id']])->update(['status'=>3,'log'=>$this->error]);
                }
            endforeach;

            return true;
        }
    }

    private function receiveOneBonus($data){
        $uid = $data['effect_uid'];
        $operateId = $data['id'];
        $coinId = $data['coin_id'];
        $amount = $data['amount'];
        $operate = $data['bonus_name'];
        $remark = $data['remark'];

        $coin_name = Coin::coinData($coinId)['coin_name'];
        $bonus_tag = Bonus::bonusData($operate)['bonus_tag'];

        // 增加账户金额
        $memberCoinModel = model('member_coin');

        $memberCoinModel->startTrans();
        try{
            $where = ['uid'=>$uid,'coin_id'=>$coinId];
            $beforeAmount = $memberCoinModel->where($where)->value('amount');
            $memberCoinModel->where($where)->setInc('amount',$amount);
            $afterAmount = $memberCoinModel->where($where)->value('amount');

            // 资金变动记录
            $coin_record = [
                'operate_id' => $operateId,
                'uid' => $uid,
                'coin_id' => $coinId,
                'amount' => $amount,
                'operate' => $operate,
                'before_amount' => $beforeAmount,
                'after_amount' => $afterAmount,
                'remark' => $remark,
                'flag' => 'inc'
            ];
            model('member_coin_record')->allowField(true)->save($coin_record);

            $memberCoinModel->commit();
        }catch(\Exception $e){
            $memberCoinModel->rollback();
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }

}
